<?php

namespace app\index\controller;

use think\Controller;


class Pay {
    protected $appid = '';//小程序id
    protected $appkey = '';//小程序key
    protected $mch_id = '';//商户号
    protected $mch_key = '';//支付秘钥

    
    public function __construct()
    {
        $this->appid = "wxd5d47d91e606786c";
        $this->appkey = "5bb70c07f3d2da95745124aeaa699ff0";
        $this->mch_id = "1611281066";
        $this->mch_key = "3a0a8dfdeae19033da914e8975815c60";
    }

    
    //微信支付
    public function pay()
    {
        include "../extend/WeChatDeveloper/include.php";
        $post = input("post.");
        $openid = $post['u_token'];
        $car_qr_id = $post['car_qr_id'];
         
        // $car_qr_id = 10;
        // $openid = "oxkCM4gClPsA2BzOKzA2L5UBF0aU";
        $total_fee = 0.01;
        $out_trade_no = date("YmdHis").round("1000", "9999");
        $config = [
        'token'          => 'longtao',
        'appid'          => $this->appid,
        'appsecret'      => $this->appkey,
        'encodingaeskey' => 'W8rSVcqWmJUTH1aCecOZsPygvsdXvQU3MbzLM1YVGE4',
        // 配置商户支付参数（可选，在使用支付功能时需要）
        'mch_id'         => $this->mch_id,
        'mch_key'        => $this->mch_key
    ];
    
        //查询用户信息
        $weiuser = DB("weixin_user")->where(['u_token' => $openid])->find();
        //查询二维码所属
        $qrinfo = DB("huabo_store")->where(['qr_id' => $car_qr_id])->find();
        
        //形成订单记录
        DB("orders")->insert(["order_num" => $out_trade_no,'sell_id' => $qrinfo['sell_id'],'store_id' => $qrinfo['store_id'],'qr_id' => $car_qr_id,"total" =>$total_fee*100,"weixin_user"=>$weiuser['id'],"create_time"=>time()]);
        try {
            // 创建接口实例
            $wechat = new \WeChat\Pay($config);

            // 组装参数，可以参考官方商户文档
            $options = [
            'body'             => '充值',
            'out_trade_no'     => $out_trade_no,
            'total_fee'        => $total_fee*100,//元变分
            'openid'           => $openid,
            'trade_type'       => 'JSAPI',
            'notify_url'       => 'https://zebra.beijing171.com/index.php/index/pay/notify',
            'spbill_create_ip' => '81.68.143.119',
        ];
        
            // 尝试创建订单
            $result = $wechat->createOrder($options);
            //成功
            if ($result['return_code'] == 'SUCCESS') {
                $prepay_id = $result['prepay_id'];
                // 创建微信端发起支付参数及签名
                $options = $wechat->createParamsForJsApi($prepay_id);

                // 微信端发起支付参数及签名JSON化
                $result = ['code' => 200, 'msg' => '操作成功', 'data' => $options];
                $params = json_encode($result);
                echo $params;
                die;
            } else {
                $this->error($result['return_msg']);
            }
        } catch (Exception $e) {
        
        // 出错啦，处理下吧
            echo $e->getMessage() . PHP_EOL;
        }
    }

    //支付回調
    public function notify()
    {
        set_time_limit(0);
        include "../extend/WeChatDeveloper/include.php";
        $config = [
        'token'          => 'longtao',
        'appid'          => $this->appid,
        'appsecret'      => $this->appkey,
        'encodingaeskey' => 'W8rSVcqWmJUTH1aCecOZsPygvsdXvQU3MbzLM1YVGE4',
        // 配置商户支付参数（可选，在使用支付功能时需要）
        'mch_id'         => $this->mch_id,
        'mch_key'        => $this->mch_key
        ];
    
        $wechat = new \WeChat\Pay($config);
        $result = $wechat->getNotify();
        
        if ($result) {
            // $result['out_trade_no'] = "202209271113161000";
            $pay_info = DB('orders')->where("order_num='{$result['out_trade_no']}'")->find();
            if ($pay_info['pay_status'] == 1) {
                //此订单已完成回调
                exit;
            }
           
            $data['id'] = $pay_info['id'];
            $data['pay_status'] = 1;
            $data['pay_time'] = time();
            DB('orders')->update($data);
            //更新绑定数据
            $bind = DB("bind")->where(['qr_id' => $pay_info['qr_id']])->find();
            
            //账户余额累加
            DB('sell_user')->where(['id' => $pay_info['sell_id']])->setInc('money',$pay_info['total']/100);
            
            
            if($bind['expire_is'] == 1){
                //已过期充值
                $enddate = date("Y-m-d H:i:s",strtotime("+12 months"));
                DB("bind")->where(['qr_id' => $pay_info['qr_id']])->update(['expire_is' => 0, "expire_time" => $enddate]);
            } else {
                //未过期充值
                $enddate = date("Y-m-d H:i:s",strtotime("+12 months",strtotime($bind['expire_time'])));
                // echo $enddate;die;
                DB("bind")->where(['qr_id' => $pay_info['qr_id']])->update(['expire_is' => 0, "expire_time" => $enddate]);
            }
            
        }
        
    }

}

